<script setup>
import { ref, onMounted, watch, onUnmounted } from "vue";
import ChatTalkUser from "@/components/chat/TalkUser.vue";
import ChatWindow from "@/components/chat/Window.vue";
import orderMsgIcon from "@/assets/order-msg.png";
import logoSmall from "@/assets/logo-small.png";
import { useMsg } from "@/store/useMsg";
import { useSocketStore } from "@/store/useSocketStore";
import { storeToRefs } from "pinia";
import { nextTick } from "vue";
const msgStore = useMsg();
const socketStore = useSocketStore();
const { talkList, currentImKey } = storeToRefs(msgStore);
//
const activeUser = ref({});
const changeTalkUser = (talkItem) => {
  activeUser.value = talkItem;
};

const timer = ref(null);
onMounted(() => {
  console.log("onMounted");
  nextTick(() => {
    setTimeout(() => {
      getTalkList();
    }, 1000);
  });
  timer.value = setInterval(() => {
    onlineReset();
  }, 5000);
});

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});

// watch(talkList, (newVal) => {
//   if (!currentImKey.value) {
//     msgStore.setCurrentImKey(newVal[0].imKey);
//   }
// });

// 获取聊天列表
const getTalkList = () => {
  socketStore.emit("chatList", {}, (res) => {
    msgStore.setTalkList(res.data);
  });
};

// 刷新在线状态
const onlineReset = () => {
  const userIds = talkList.value
    .filter((item) => item.userType === 2)
    .map((item) => item.imKey);
  if (userIds.length === 0) return;
  socketStore.emit("userOnline", userIds, (res) => {
    if (res.code === 200) {
      msgStore.setOnlineStatus(res.data);
    }
  });
};
</script>

<template>
  <div class="chat">
    <div class="talk-list">
      <ChatTalkUser
        v-for="item of talkList"
        :key="item.user"
        :talkItem="item"
        :activeUser="activeUser"
        @click="changeTalkUser(item)"
      />
    </div>
    <div class="chat-box">
      <ChatWindow v-if="msgStore.getCurrentImKey" :activeUser="activeUser" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.chat {
  flex: 1;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  display: flex;
  box-sizing: border-box;
}
.talk-list {
  flex: 0 0 260px;
  border-right: 1px solid #ededee;
  padding: 12px;
  box-sizing: border-box;
}
.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>
